package cn.enjoy.design.behavior.strategy.springBeanPostProcessor;

import cn.enjoy.design.structure.proxy.listener.FlowStateListener;
import cn.enjoy.design.structure.proxy.manager.FlowStateManager;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.NonNull;

/**
 * 利用BeanPostProcessor接口，在bean初始化注入到容器后，在执行postProcessAfterInitialization()钩子函数
 *
 * @author K
 * @date 2021-07-18 18:07
 */
@Configuration("WorkOrderBootstrap2")
public class ProxyConfiguration implements BeanPostProcessor {

    private FlowStateManager stateManager = new FlowStateManager();

    /**
     * 注入状态管理器
     */
    @Bean("flowStateManager2")
    public FlowStateManager flowStateManager2() {
        return stateManager;
    }

    /**
     * Bean初始化后的回调，此处是判断Bean是否是FlowStateListener的实例，是的话就加入到stateManager
     */
    @Override
    public Object postProcessAfterInitialization(@NonNull Object bean, @NonNull String beanName) throws BeansException {
        if (bean instanceof FlowStateListener) {
            stateManager.register((FlowStateListener<?>) bean);
        }
        return bean;
    }

}
